﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp4.Models
{
    public class Time
    {
        /// <summary>
        /// 查询性能计数器的当前值
        /// </summary>
        /// <param name="lpPerformanceCount"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern bool QueryPerformanceCounter([In, Out] ref long lpPerformanceCount);
        [DllImport("kernel32.dll")]
        private static extern bool QueryPerformanceFrequency([In, Out] ref long lpFrequency);

        static Time()
        {
            startupTicks = ticks;
        }

        /// <summary>
        /// 总运行时间 计数
        /// </summary>
        private static long _frameCount = 0;
        public static long frameCount { get => _frameCount; }

        private static long startupTicks = 0;

        private static long freq = 0;

        /// <summary>
        /// 计时器
        /// </summary>
        public static long ticks
        {
            get
            {
                long f = freq;
                if (f == 0)
                {
                    if (QueryPerformanceFrequency(ref f))
                    {
                        freq = f;
                    }
                    else
                    {
                        freq = -1;
                    }
                }
                if (f == -1)
                {
                    return Environment.TickCount * 10000;
                }
                long c = 0;
                QueryPerformanceCounter(ref c);
                return (long)(((double)c) * 1000 * 10000 / ((double)f));
            }
        }

        private static long lastTick = 0;

        private static float _deltaTime = 0;
        public static float deltaTime { get => _deltaTime; }

        /// <summary>
        /// 总运行时间 秒
        /// </summary>
        private static float _time = 0;
        public static float time { get => _time; }

        /// <summary>
        /// 总运行时间 秒
        /// </summary>
        public static float realtimeSinceStartup
        {
            get
            {
                long _ticks = ticks;
                return (_ticks - startupTicks) / 10000000f;
            }
        }

        public static void Tick()
        {
            long _ticks = ticks;

            _frameCount++;
            if (_frameCount == long.MaxValue)
            {
                _frameCount = 0;
            }

            if (lastTick == 0)
            {
                lastTick = _ticks;
            }

            _deltaTime = (_ticks - lastTick) / 10000000f;
            _time = (_ticks - startupTicks) / 10000000f;

            lastTick = _ticks;
        }
    }
}
